package com.xxs.controller.shop.api;

import com.xxs.common.WebUtils;
import com.xxs.model.Admin;
import com.xxs.oauth.OauthQQ;
import com.xxs.oauth.OauthSina;
import com.xxs.utils.TokenUtil;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.core.Controller;

public class OauthController extends Controller {
	
	//OAuth2.0标准协议建议，利用state参数来防止CSRF攻击。可存储于session或其他cache中
	private static final String SESSION_STATE = "_SESSION_STATE_QQ_";
	
	public void toQQ(){
		try {
			String state = TokenUtil.randomState();
			setSessionAttr(SESSION_STATE, state);
			redirect(OauthQQ.me().getAuthorizeUrl(state));
		} catch (Exception e) {
			redirect("/");
		}
	}
    public void toSina(){
    	try {
            String state = TokenUtil.randomState();
            setSessionAttr(SESSION_STATE, state);
            redirect(OauthSina.me().getAuthorizeUrl(state));
        } catch (Exception e) {
            redirect("/");
        }
    }
    /**
     * 腾讯回调
     * @Title: callback
     * @param     设定文件
     * @return void    返回类型
     * @throws
     * 返回json:<url>http://wiki.connect.qq.com/get_user_info</url>
     */
    public void sinacallback() {
        String code = getPara("code");
        String state = getPara("state");
        String session_state = getSessionAttr(SESSION_STATE);
        // 取消了授权
//        if (StringUtils.isBlank(state) || StringUtils.isBlank(session_state) || !state.equals(session_state) || StringUtils.isBlank(code)) {
//            redirect("/");
//            return;
//        }
        removeSessionAttr(SESSION_STATE);
        try{
            JSONObject userInfo = OauthSina.me().getUserInfoByCode(code);
//            log.error(userInfo);
            String type = "sina";
            String openid = userInfo.getString("openid");
            String nickname = userInfo.getString("nickname");
            String photoUrl = userInfo.getString("figureurl_2");
            System.out.println("openID:"+openid);
            System.out.println("nickname:"+nickname);
            System.out.println("photoUrl:"+photoUrl);
            
            // 将相关信息存储数据库...
            Admin user = new Admin();
            user.set("username", nickname);
            user.set("password", "123123");
            user.set("headImg", photoUrl);
            user.mySave();
            setAttr("msg", "恭喜你，注册成功，请登录：");
            WebUtils.loginUser(this, user, true);
        }catch(Exception e){
//            log.error(e);
        	System.out.println(e.toString());
        }
        redirect("/");
    }
}
